<template>
    <div>
      <CTable
        ref="base"
        :columns="columns"
        :data="data"
        @fetch="fetch"
      >
        <template slot="headerLeft">
          <a-breadcrumb>
            <a-breadcrumb-item><router-link to="/platform/platformmanagement">客户管理</router-link></a-breadcrumb-item>
            <a-breadcrumb-item><router-link to="/platform/packagemanagement">套餐管理</router-link></a-breadcrumb-item>
          </a-breadcrumb>
        </template>
        <a-space>
          <a-button type="primary" @click="changeModel()">
            新增套餐
          </a-button>
        </a-space>
        <template slot="name" slot-scope="{record}">
          <a-button type="link" @click="openDetail(record)">{{record.name}}</a-button>
        </template>
        <template slot="action" slot-scope="{record}">
          <a-button type="link" @click="changeModel(record)">编辑</a-button>
          <a-button type="link" @click="deleteRecord(record)">删除</a-button>
        </template>
      </CTable>
      <a-modal
        v-model="detailShow"
        title="套餐详情"
        :width="480"
        :destroy-on-close="true"
        :footer="null"
      >
        <div class="cmodal">
          <a-form-model layout="inline">
            <a-form-model-item
              label="套餐名称"
              style="width:100%;"
            >
              <span>{{ detail.name }}</span>
            </a-form-model-item>
            <a-form-model-item label="套餐权限">
              <a-tree
                :tree-data="detail.treeData"
                :defaultExpandAll="true"
                v-model="detail.functionIdList"
                class="detailDisplay"
                checkable
                :checkStrictly="true"
                :replaceFields="{children:'children', title:'name', key:'id' }"
              />
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-modal>
      <a-modal
        v-model="show"
        :title="recordData.id ? '编辑套餐' : '新增套餐'"
        :width="480"
        :destroy-on-close="true"
        @ok="handleOk"
        :confirmLoading="modalLoading"
        :afterClose="()=>this.modalLoading = false"
      >
        <div class="cmodal">
          <a-form-model
            ref="editForm"
            :model="form"
            :rules="rules"
            layout="vertical"
          >
            <a-form-model-item
              label="设置套餐名称"
              prop="name"
            >
              <a-input
                v-model="form.name"
                placeholder="请输入套餐名称"
              />
            </a-form-model-item>
            <a-form-model-item
              label="选择功能模块"
              prop="functionIdList"
            >
              <a-tree
                v-model="form.functionIdList"
                :replaceFields="{children:'children', title:'name', key:'id' }"
                checkable
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :tree-data="treeData"
                @expand="onExpand"
                @select="onSelect"
                @check="onCheck"
                :checkStrictly="true"
              />
            </a-form-model-item>
            <a-form-model-item
              label="设置服务时长"
              prop="duration"
            >
              <a-select v-model="form.duration">
                <a-select-option v-for="item in durationList" :key="item.key" :value="item.key">
                  {{item.text}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-modal>
    </div>
</template>

<script>
import CTable from '../Template/c-table';
import {Modal} from 'ant-design-vue';

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'no' }
  },
  {
    title: '套餐名称',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '服务时长',
    dataIndex: 'duration'
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
];

const data = [];

const treeData = [];

export default {
  name: 'PackageManagement',
  components: {CTable},
  watch: {
    show() {
      if(!this.show) {
        this.setList = new Set([]);
      }
    }
  },
  data() {
    return {
      data,
      columns,
      show: false,
      detailShow: false,
      modalLoading: false,
      recordData: {},
      durationList: [
        {
          key: '一个月',
          text: '一个月'
        },
        {
          key: '三个月',
          text: '三个月'
        },
        {
          key: '半年',
          text: '半年'
        },
        {
          key: '一年',
          text: '一年'
        },
        {
          key: '三年',
          text: '三年'
        },
        {
          key: '永久',
          text: '永久'
        }
      ],
      form: {
        name: '',
        duration: '',
        functionIdList: []
      },
      rules: {
        name: [
          {required: true, message: '请输入', trigger: 'blur' },
          {max: 16, message: '请输入不超过16个字符', trigger: 'blur' }
        ],
        duration: [
          {required: true, message: '请输入', trigger: 'blur' }
        ],
        functionIdList: [
          {required: true, message: '请选择', trigger: 'blur', type: 'array' }
        ]
      },
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      treeData,
      detail: {
        treeData: [],
        name: ''
      },
      setList: new Set([])
    };
  },
  created() {
    this.$api.setMeal.selList()
      .then(res => {
        if(res) {
          if(Array.isArray(res)) {
            this.treeData = this.treeDataPath(res, '');
          }
        }
      });
  },
  methods: {
    onCheck(checkedKeys, {checked, node}) {
      // eslint-disable-next-line consistent-this
      function deepId(list, that) {
        if(!list) {
          return;
        }
        list.forEach(item => {
          that.setList.delete(item.id);
          if(item.children) {
            deepId(item.children, that);
          }
        });
      }
      // eslint-disable-next-line consistent-this
      function addId(list, that) {
        if(!list) {
          return;
        }
        list.forEach(item => {
          that.setList.add(item.id);
          if(item.children) {
            addId(item.children, that);
          }
        });
      }

      if(checked) {
        node.dataRef.path.split('-').forEach(item => {
          this.setList.add(+item);
        });
        addId(node.dataRef.children, this);
        this.form.functionIdList = Array.from(this.setList);
      } else{
        this.setList.delete(node.dataRef.id);
        deepId(node.dataRef.children, this);
        this.form.functionIdList = Array.from(this.setList);
      }
    },
    onExpand(expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onSelect(selectedKeys, info) {
      console.log('onSelect', info);
      this.selectedKeys = selectedKeys;
    },
    // eslint-disable-next-line no-shadow
    treeDataPath(treeData, path) {
      treeData.forEach(item => {
        item.path = `${path ? `${path}-` : ''}${item.id}`;
        if(item.children) {
          this.treeDataPath(item.children, item.path);
        }
      });

      return treeData;
    },
    openDetail(record) {
      this.detail = {
        name: record.name,
        treeData: this.treeDataPath(this.treeData, ''),
        functionIdList: record.functionIdList
      };
      this.detailShow = true;
    },
    deleteRecord(record) {
      const deleteType = {
        'warning': {
          title: `不可删除套餐${record.name}`,
          content: '该套餐正在使用, 不可被删除!',
          okType: 'default',
          okText: '取消'
        },
        'confirm': {
          title: `确定删除套餐${record.name}`,
          content: `套餐${record.name}已无企业使用，可以对其进行删除操作，您确认要删除该套餐？`,
          okType: 'primary',
          okText: '确定'
        }
      };
      this.$api.setMeal.deleteJudge({setMealId: record.id}).then(resType => {
        const type = resType ? 'confirm' : 'warning';
        const params = deleteType[type];
        Modal[type]({
          title: params.title,
          content: params.content,
          okType: params.okType,
          // eslint-disable-next-line consistent-return
          onOk: () => {
            if(type === 'warning') {
              return Promise.resolve();
            }
            this.$api.setMeal.delete({setMealId: record.id})
            // eslint-disable-next-line consistent-return
              .then(res => {
                if(res) {
                  return this.$refs.base.fetch();
                }
              })
              .catch(() => Promise.reject());

          },
          cancelText: params.cancelText,
          okText: params.okText
        });
      });
    },
    handleOk() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.modalLoading = true;
          this.$api.setMeal.addAndUpdate({
            ...this.form,
            id: this.recordData.id
          }).then(res => {
            if(res) {
              this.show = false;
              this.$message.info('操作成功');
              this.$refs.base.fetch();
            }
          })
            .catch(() => this.modalLoading = false);
        }
      });
    },
    changeModel(recordData) {
      this.recordData = recordData || {};
      for(let item in this.form) {
        this.form[item] = recordData ?
          recordData[item] :
          item === 'functionIdList' ? [] : '';
      }
      if(this.recordData.functionIdList) {
        this.setList = new Set(this.recordData.functionIdList);
      }
      this.show = true;
    },
    fetch(params) {
      this.$api.setMeal.list(params)
        .then(res => {
          if(!res) {
            res = {list: [], total: 0};
          }
          this.data = res.data;
          this.$refs.base.fetchSuccess(res.total);
        })
        .finally(() => {
          this.$refs.base.fetchFinally();
        });
    }
  }
};

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
/deep/.detailDisplay{
  .ant-tree-checkbox, .ant-tree-checkbox-indeterminate{
    display: none;
  }
  li:not(.ant-tree-treenode-checkbox-checked):not(.ant-tree-treenode-checkbox-indeterminate){
    display: none;
  }
}
.cmodal{
  width: 100%;
  padding: 0 76px;
}
</style>
